<template>
    <div class="photo-box">
        <el-row :gutter="24">
            <el-col :span="12" class="photo-tab">
                <el-tabs v-model="activeName" type="card" stretch @tab-click="handleClick">
                    <el-tab-pane v-for="(tabItem, tabInd) in tabList" :key="tabItem.photoClass"
                        :customType="tabItem.photoClass" :label="`${tabItem.label}(${tabItem.imgLen || 0})`"
                        :name="tabItem.name">
                        <el-row class="photo-operate">
                            <el-col :span="tabItem.photoClass > 0 ? 6 : 8">
                                <i class="el-icon-refresh-left"></i>
                                <span @click="stackImg(tabInd)"> 退回</span>
                            </el-col>
                            <el-col :span="tabItem.photoClass > 0 ? 6 : 8">
                                <span style="color:#f5bf4f" @click="imgDelete(tabInd)">删除</span>
                            </el-col>
                            <el-col :span="tabItem.photoClass > 0 ? 6 : 8" v-show="tabItem.photoClass > 0">
                                <el-checkbox>未上传</el-checkbox>
                            </el-col>
                            <el-col :span="tabItem.photoClass > 0 ? 6 : 8">
                                <el-checkbox>全选</el-checkbox>
                            </el-col>
                        </el-row>
                        <el-row class="photo-scroll scroll-case-list" v-if="tabItem.imgList && tabItem.photoClass <= 0"
                            v-loading="imgLoading">
                            <el-col :span="12" v-for=" (imgItem, index) in tabItem.imgList" :key="imgItem.fileId">
                                <div class="img-content" @click="chooseImg(tabInd, index)">
                                    <el-image :src="imgItem.thumbUrl" fit="fill" @dblclick="viewImage(index)">
                                        <div slot="error" class="image-slot">
                                            <i class="el-icon-picture-outline"></i>
                                        </div>
                                    </el-image>
                                    <div class="img-footer">
                                        <span>{{ imgItem.statusDesc }}</span>
                                        <span v-if="tabItem.photoClass == 0">{{ imgItem.sortoutDesc }}</span>
                                        <el-checkbox v-model="imgItem.checked"
                                            @change="chooseImg(tabInd, index)"></el-checkbox>
                                    </div>
                                </div>
                            </el-col>
                        </el-row>
                        <div v-else class=" photo-scroll scroll-case-list" v-loading="imgLoading">
                            <el-collapse accordion v-if="tabItem.photoClass > 0" @change="collapseChange"
                                style="margin-top:40px">
                                <!-- SortTypeData[tabItem.photoClass].children -->
                                <el-collapse-item v-for="sortItem in filterSortList" :key="sortItem.id"
                                    :name="sortItem.id">
                                    <template slot="title">
                                        <div :class="collapse == sortItem.id ? 'coll-active' : ''"> <i
                                                :class="collapse == sortItem.id ? 'el-icon-folder-opened' : 'el-icon-folder'"></i>
                                            {{ sortItem.value }}</div>
                                    </template>
                                    <el-row v-if="tabItem.imgList">
                                        <el-col :span="12"
                                            v-for=" (imgItem, index) in filteredImgList(tabItem.imgList, sortItem)"
                                            :key="imgItem.fileId">
                                            <div class="img-content" @click="chooseImg(tabInd, index)">
                                                <el-image :src="imgItem.thumbUrl" fit="fill"
                                                    @dblclick="viewImage(index)">
                                                    <div slot="error" class="image-slot">
                                                        <i class="el-icon-picture-outline"></i>
                                                    </div>
                                                </el-image>
                                                <div class="img-footer">
                                                    <span>{{ imgItem.statusDesc }}</span>
                                                    <span v-if="tabItem.photoClass === 0">{{ imgItem.sortoutDesc
                                                        }}</span>
                                                    <el-checkbox v-model="imgItem.checked"
                                                        @change="chooseImg(tabInd, index)"></el-checkbox>
                                                </div>
                                            </div>
                                        </el-col>
                                    </el-row>
                                </el-collapse-item>
                            </el-collapse>
                        </div>
                    </el-tab-pane>
                </el-tabs>
            </el-col>
            <el-col :span="12">
                <sort-type @sort-click="stackImg" />
            </el-col>
        </el-row>
        <viewer v-if="viewerFlag" ref="viewer" :url-list="bigphotoList" :initial-index="initialIndex" :on-close="close"
            @delete="handleDeleteImgId" />
    </div>
</template>
<script>
import { mapState } from 'vuex'
import { imgDelete, stackImg, imgDownload, choiceType, loadCaseImgs } from '@/api/case'
import sortType from './sortTypeView.vue'
import SortTypeData from "./SortTypeData";
import viewer from "@/components/app-image-viewer/index"; // 图片详细组件
export default {
    components: {
        viewer,
        sortType
    },
    props: ["photoList", "taskId"],
    data() {
        return {
            viewerFlag: false,
            imgLoading: false,
            activeName: 'all',
            sortPhotoCheck: '',
            initialIndex: 0,
            tabIndex: 0,
            bigphotoList: [],
            imgList: [],
            collapse: '',
            SortTypeData: SortTypeData,
            // sortList: [],
            tabList: [{
                photoClass: '0',
                label: '全部',
                name: 'all',
            }, {
                photoClass: '-1',
                label: '未分拣',
                name: 'noSort',
            }, {
                photoClass: '2',
                label: '单证',
                name: 'card',
            }, {
                photoClass: '1',
                label: '车损',
                name: 'carLoss',
            }]

        }
    },
    created() {

    },
    computed: {
        ...mapState({
            userInfo: state => state.user.userInfo,
        }),
        filterSortList() {
            return this.tabList[this.tabIndex].photoClass === '1' ? this.SortTypeData[0].children : this.SortTypeData[1].children
        },
    },
    methods: {
        viewImage(ind) {
            this.viewerFlag = true;
            this.bigphotoList = this.tabList[0].imgList
            this.initialIndex = ind
        },
        setCount(list) {
            const countResult = this.tabList.map(tab => {
                let count = 0;
                list.forEach(item => {
                    if (item.photoClass === tab.photoClass) {
                        count++;
                    }
                });
                return count;
            });
            this.tabList = this.tabList.map((tab, index) => {
                if (index === 0) {
                    tab.imgLen = countResult.reduce((acc, cur) => acc + cur, 0);
                } else {
                    tab.imgLen = countResult[index];
                }
                return tab
            });
        },
        handlePhotoList(list) {
            if (list) {
                const statusMap = {
                    "-2": "未上传",
                    "-1": "待上传",
                    "0": "上传失败",
                    "1": "上传成功"
                };
                const sortoutMap = {
                    "-1": "未分拣",
                    "1": "查勘",
                    "2": "单证"
                };
                list.forEach(imgItem => {
                    imgItem.statusDesc = statusMap[imgItem.status] || imgItem.statusDesc;
                    imgItem.sortoutDesc = sortoutMap[imgItem.photoClass] || imgItem.sortoutDesc;
                    imgItem.checked = false
                });
                this.setCount(list)
                this.imgList = list;
                this.tabList[0].imgList = list
            }
        },
        handleClick(tab) {
            this.collapse = ''
            const tabIndex = this.tabIndex = Number(tab.index);
            const customTypeValue = tab.$attrs.customType;
            if (Number.isInteger(tabIndex) && tabIndex > 0) {
                this.tabList[tabIndex].imgList = this.imgList.filter(item => item.photoClass === customTypeValue);
            } else {
                this.tabList[tabIndex].imgList = this.imgList;
            }
            this.$emit('tab-changed', tabIndex);
        },
        collapseChange(active) {
            this.collapse = active;
        },
        imgDownload(i) {
            const imageIds = this.tabList[i].imgList.filter(item => item.checked).map(item => item.fileId).join(',')
            if (imageIds) {
                const loading = this.$loading({
                    lock: true,
                    text: '正在压缩，请稍后',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                let params = {
                    taskId: this.taskId,
                    imageIds: imageIds
                }
                imgDownload(params).then(res => {
                    loading.close()
                    if (res.zipUrl) {
                        const a = document.createElement('a');
                        a.href = res.zipUrl;
                        // a.download = '文件名.zip'; 
                        a.style.display = 'none';
                        document.body.appendChild(a);
                        a.click();
                        document.body.removeChild(a);
                    } else {
                        this.$message({
                            message: res.msg,
                            type: 'error'
                        })
                    }
                }).catch(() => {
                    loading.close()
                })
            } else {
                this.$message("请先选中需要下载的照片！")
            }
        },
        // 上传到集审
        choiceType(i) {
            const imageIds = this.tabList[i].imgList.filter(item => item.checked).map(item => item.fileId).join(',')
            if (imageIds) {
                const loading = this.$loading({
                    lock: true,
                    text: '正在连接，请稍后',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.7)'
                });
                setTimeout(() => {
                    loading.close()
                })
                const params = {
                    taskId: this.taskId,
                    userId: this.userInfo.userId,
                    groupExt1: this.userInfo.groupExt1,
                    workNumber: '',
                    lFlag: ''
                    // imagelist: imageIds
                }
                choiceType()
            } else {
                this.$message("请先选中需要上传的照片！")
            }
            // newImgInclude
        },
        filteredImgList(imgList, sortItem) {
            return imgList.filter(imgItem => (imgItem.photoClass == sortItem.parlabel && imgItem.ciapTaskType === sortItem.caip && imgItem.dispatchItemType == sortItem.dispatchItemType))
        },


        stackImg(sortData) {
            this.imgLoading = true
            const imageList = this.tabList[this.tabIndex].imgList.filter(item => item.checked)
            const noSorts = imageList.filter(item => { item.status != -2 })
            if (noSorts && noSorts.length > 0) {
                this.$message({
                    message: '图片含已上传图片，不可再次分拣',
                    type: 'warning'
                })
            } else {
                const comfirmMsg = '未分拣'
                if (imageList && imageList.length > 0) {
                    this.$confirm(`您确定要分拣为【${comfirmMsg}】状态吗?`, '提示', {
                        confirmButtonText: '确定',
                        cancelButtonText: '取消',
                        type: 'warning'
                    }).then(() => {
                        imageList.forEach(item => {
                            item.photoClass = sortData.photoClass
                            item.ciapTaskType = sortData.caip
                            item.dispatchItemType = sortData.dispatchItemType || ''
                            item.lossPart = sortData.dispatchItemType == '4' ? sortData.label : ''
                        })
                        this.imgLoading = false
                        let params = {
                            taskId: this.taskId,
                            imagelist: imageList
                        }
                        stackImg(params).then(() => {
                            // this.setCount()
                            loadCaseImgs({ taskId: this.taskId }).then(imgData => {
                                this.handlePhotoList(imgData.imageList)
                            })
                        })
                    })
                } else {
                    this.$message("请先选中需要分拣的照片！")
                }
            }
        },
        imgDelete(i) {
            const imageIds = this.tabList[i].imgList.filter(item => item.checked).map(item => item.fileId).join(',')
            if (imageIds) {
                this.$confirm('确认删除当前选中图片?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.imgLoading = true
                    let params = {
                        taskId: this.taskId,
                        imageIds: imageIds
                    }
                    imgDelete(params).then(res => {
                        this.imgLoading = false
                        this.$message({
                            message: '已删除',
                            type: 'success'
                        })
                        const imageIdMap = new Map(res.imageList.map(id => [id, true]));
                        const newImgList = this.tabList[i].imgList.filter(item => {
                            return !imageIdMap.has(item.fileId);
                        });
                        this.setCount(newImgList)
                        this.tabList[i].imgList = newImgList
                        this.$forceUpdate()
                    })
                })
            } else {
                this.$message("请先选中需要删除的照片！")
            }

        },
        handleDeleteImgId() {

        },
        chooseImg(tanInd, imgInd) {
            this.$set(this.tabList[tanInd].imgList[imgInd], 'checked', !(this.tabList[tanInd].imgList[imgInd].checked))
            this.$forceUpdate()
        },
        close() {
            this.viewerFlag = false;
        }
    },
    watch: {
        photoList: {
            handler(list) {
                this.activeName = 'all'
                this.handlePhotoList(list)
            },
        },
    },
}
</script>
<style lang='scss' scoped>
.photo-box {
    width: 100%;

    .photo-tab {
        border-right: 1px solid #eee;

        ::v-deep {
            .el-tabs__header {
                margin: 0;
            }

            .el-tabs__nav-wrap {
                padding-left: 0;
            }

            .el-collapse-item__header {
                text-indent: 1em;
                font-size: 14px;
            }

            .el-tabs__item {
                height: 35px;
                line-height: 35px;
                padding: 0 15px;
            }

            .el-tabs__item.is-active {
                border-bottom: none;
                color: #000;
                font-weight: bold;
            }

            .el-tabs__item:hover {
                color: #000;
            }

            .el-row {
                margin-top: 10px;
            }

            .el-col {
                text-align: center;

                .is-checked .el-checkbox__inner {
                    border-color: #FF4E33;
                    background-color: #FF4E33;
                }

                .is-checked+.el-checkbox__label {
                    color: #FF4E33
                }
            }
        }
    }

    .photo-operate .el-col {
        cursor: pointer;
    }

    .photo-scroll {
        height: 60vh;
        overflow-y: auto;

        .coll-active {
            color: #FF4E33
        }
    }
}

.img-content {
    width: 93%;
    margin: 5px;
    border-radius: 5px;
    position: relative;

    .img-footer {
        display: flex;
        justify-content: space-between;
        align-items: center;
        width: 100%;
        height: 30px;
        background-color: rgba(0, 0, 0, 0.5);
        position: absolute;
        bottom: 0;
        padding: 0 5px;

        >* {
            color: #fff;
        }
    }

    ::v-deep {
        .el-image {
            width: 100%;
            max-height: 140px;
            border-radius: 5px;

            img {
                height: 140px;
            }
        }
    }
}
</style>
